<?php
/**
 * Created by PhpStorm.
 * User: l-ht
 * Date: 2018/10/28
 * Time: 14:29
 */

namespace app\index\controller;


use app\index\model\Album;
use app\index\model\Thread;
use app\index\model\Like;
use app\index\model\User;
use think\Request;
use app\index\model\Post as PostModel;

class Post extends Base
{
    protected $_thread;

    public function __construct(PostModel $thread)
    {
        $this->_thread = $thread;
    }

    //发表回复
    public function publish(Request $request)
    {
        $data = $request->param();

        $this->_thread->tid   = $data['tid'];
        $this->_thread->typeid   = $data['typeid'];
        $this->_thread->authorid  = $data['uid'];
        $this->_thread->message = $data['message'];
        //$this->_thread->useip   = $data['useip'];
        //$this->_thread->create_time     = time();

        $res = $this->_thread->save();
		if( $res ){
			 Thread::get($this->_thread->tid)->setInc('replies');
			 $this->makePoint($data['uid'],$data['tid'],2);
			 return $this->_toSuccess(['tid' => $this->_thread->tid,'msg' => '发表成功',]);
		}
 
    }
    //加载更多回复
    public function loadpost(Request $request)
    {
		$tid = input('tid');
		$uid = input('uid');
		$page = input('page');
		if($page>0){
			$limit = $page*4;
		}else{
			$limit = 4;
		}
        //查询回复
		$total = PostModel::where('tid',$tid)->count()+4;
		if($total<$limit){
				return $this->_toError(['msg' => '没有更多了！']);
			}
		$list = PostModel::all(function($query) use($tid,$limit){
					$query->where('tid',$tid)->limit($limit)->order('pid', 'desc');
				});
		$list = $list->toArray();
		//关联用户头像 用户名
		$lists = [];
		foreach($list as $usr){
			$arrname = User::get($usr['authorid']);
			$usr['url'] = $arrname['avatar'];
			$usr['author'] = $arrname['nickname'];
			//查询是否点赞
			$arrlike = Like::get(["tid"=>$tid,"uid"=>$uid,"pid"=>$usr['pid']]);
			$usr['like'] = $arrlike ? 1 : 0;
			$lastime = strtotime($usr['create_time']);
			$usr['lastime'] = $this->lastime($lastime);
			$lists[] = $usr;
		}
		if( $lists ){
			return $this->_toSuccess(['list' => $lists,'msg' => '获取成功']);
		}
 
    }	
    
	//点赞
    public function like()
    {
		$tid = input('tid');
		$uid = input('uid');
		$pid = input('pid');
	    $arr = Like::get(["uid"=>$uid,"tid"=>$tid,"pid"=>$pid]);
		if($arr){
			 $res = $arr->delete();
			 if($res){
				PostModel::get($pid)->setDec('goodnums');
				Like::destroy(['uid' => $uid,'tid' => $tid,'pid' => $pid]);
				return $this->_toError(['msg' => '取消成功']);
				
			}else{
				return $this->_toError(['msg' => '取消失败']);
			}
		}else{
			$like  = new Like;
			$like->tid = $tid;
			$like->uid = $uid;
			$like->pid = $pid;
			$like->atime = time();
			$res = $like->save();
			if($res){
				PostModel::get($pid)->setInc('goodnums');
				return $this->_toError(['msg' => '点赞成功']);
			}else{
				return $this->_toError(['msg' => '点赞失败']);
			}
			
		}
	}    
}